package utils;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:咭咭熊
 * Date:2021 - 08 - 01
 * Time:15:57
 */

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/***
 * 封装连接数据库的操作方法
 */
public class DBUtils {
    private static MysqlDataSource dataSource = null;

    /***
     * 1.得到连接的通用方法
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        if(dataSource == null){
            //第一次调用
            dataSource = new MysqlDataSource();
            dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/java18blog?charaterEncoding=utf-8&useSSL=true");
            dataSource.setUser("root");
            dataSource.setPassword("root");
        }
        return dataSource.getConnection();
    }

    /***
     * 2.通用的关闭方法
     * @param connection
     * @param statement
     * @param resultSet
     * @throws SQLException
     */
    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) throws SQLException {
        if(resultSet != null) resultSet.close();
        if(statement != null) statement.close();
        if(connection != null) connection.close();
    }
}
